﻿using CJJ_BlogApiV3.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text;
using Microsoft.Extensions.Logging;

namespace Chen.IdentityServer4.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MemberController : ControllerBase
    {
        private ILogger<MemberController> _logger = null;
        public MemberController(ILogger<MemberController> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 获取会员注册的随机验证码
        /// </summary>
        /// <param name="codeKey"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public Result<string> GetLoginCode([FromQuery] string codeKey)
        {
            Result<string> data = Result<string>.Failure();
            try
            {
                var key = GetMemCacheKey(codeKey);
                //生成5位随机码
                char[] Pattern = new char[] { '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
                    'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
                string code = "";
                int n = Pattern.Length;
                Random random = new Random(Guid.NewGuid().GetHashCode());
                for (int i = 0; i < 4; i++)
                {
                    int rnd = random.Next(0, n);//取不到n-1,取不到‘Z’?
                    code += Pattern[rnd];
                }
                var codeByte = Encoding.UTF8.GetBytes(code);
                Random rdm = new Random(Guid.NewGuid().GetHashCode());
                //虽然配置的时间可能不同  增加随机 防止一起过期了

                var time = DateTime.Now.AddMinutes(5);

                TimeSpan sp = new TimeSpan(time.Ticks);
                RedisHelper.Set(key, System.Text.Encoding.UTF8.GetBytes(code), sp);

                data.Data = code;
                data.IsSucceed = true;
                data.Message = "成功";
                data.ErrorCode = 200;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取随机验证码失败");
                data.Message = "获取随机验证码失败";
            }
            return data;
        }

        /// <summary>
        /// 获取cachekey
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        private string GetMemCacheKey(string cacheKey) => $"memberKey{cacheKey}";
    }
}
